<template>
  <div class="main">
    <div class="main-title">商品库存</div>
    <div class="main-content">
      <div class="content-wrapper">
        <div class="tools-wrapper">
          <el-row>
            <el-col :span="6">
              <el-button type="primary" v-if="hasPermission('1004020102')" @click="openDialog">导入</el-button>
              <el-button type="primary" v-if="hasPermission('1004020103')" @click="exportGoods">导出</el-button>
            </el-col>
            <el-col :span="18" class="flex-box">
              <el-input class="f1" v-model="queryForm.commodityNo" placeholder="请输入商品SPU"></el-input>
              <el-input class="f1" v-model="queryForm.sku" placeholder="请输入商品SKU"></el-input>
              <el-input class="f1" v-model="queryForm.commodityName" placeholder="请输入商品名称"></el-input>
              <el-select class="f1" placeholder="请选择商品分类" v-model="queryForm.categoryId" clearable>
                <el-option v-for="(item, index) in categoryList" :key="index" :value="item.categoryId" :label="item.categoryName"></el-option>
              </el-select>
              <el-button type="primary" @click="getData">搜索</el-button>
            </el-col>
          </el-row>
        </div>
        <div class="table-wrapper">
          <el-table :data="tableData" border stripe v-loading="$store.state.isLoading">
            <el-table-column label="序号" width="60" fixed="left" align="center">
              <template slot-scope="scope">
                {{(page-1)*pageSize + scope.$index + 1}}
              </template>
            </el-table-column>
            <el-table-column label="SPU" prop="spu" align="center"></el-table-column>
            <el-table-column label="商品SKU" prop="sku" align="center"></el-table-column>
            <el-table-column label="商品名称" prop="commodityName" align="center"></el-table-column>
            <el-table-column label="所属分类" prop="categoryName" align="center"></el-table-column>
            <el-table-column label="售卖规格" prop="attributeName" align="center"></el-table-column>
            <el-table-column label="零售价" prop="sellPrice" align="center"></el-table-column>
            <el-table-column label="摆放位置" prop="position" align="center"></el-table-column>
            <el-table-column label="剩余库存" prop="stockNum" align="center" sortable></el-table-column>
            <el-table-column fixed="right" label="操作" width="150"  align="center">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="check(scope)" v-if="hasPermission('1004020104')">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <v-pagination v-if="total" :pg="page" :size="pageSize" :total="total" :views="5" @page-change="pageChange" @size-change="sizeChange"></v-pagination>
        </div>
      </div>
    </div>
    <!-- 导入库存 -->
    <el-dialog title="导入库存" width="520px" :visible.sync="importDialog" :close-on-click-modal="false">
      <el-upload
        ref="fileUploader"
        class="drag-uploader"
        drag
        :action="$api + '/sys/uploadFile'"
        :limit="1"
        :before-upload="beforeUpload"
        :on-success="uploadSuccess"
        :on-exceed="overUpload"
        multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <p>1.请先下载模板填写完善后再上传</p>
        <p>2.只允许上传<em>xls</em>格式的Excel表格文件</p>
      </el-upload>
      模板：<a :href="this.$api + '/stock/download'">下载模板</a>
      <div class="upload-result-box" v-if="resultList.length">
        <ul class="result-list">
          <li v-if="index < resultList.length - 1" v-for="(item, index) in resultList" :key="index">{{(index+1) + '、用户导入失败，失败记录为序号' + item}}</li>
          <li v-else>{{item}}</li>
        </ul>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importGoods">导入</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QS from 'qs'
import { sign } from '@/utils/sign'
export default {
  data () {
    return {
      queryForm: {
        commodityNo: '',
        commodityName: '',
        sku: '',
        categoryId: ''
      },
      sortType: 1, // 1: 默认（按照spu倒序）； 2：按库存降序； 3:按库存升序。
      tableData: [],
      categoryList: [],
      page: Number(this.$route.query.pg) || 1,
      pageSize: Number(this.$route.query.size) || 10,
      total: 0,
      importDialog: false,
      fileUrl: '', // 上传文件路径
      resultList: [] // 导入结果
    }
  },
  mounted () {
    this.getCategorys()
    this.getData()
  },
  methods: {
    // 获取库存信息
    getData () {
      this.$store.commit('setLoading', true)
      this.$http.post(this.$api + '/stock/selectiveStockInfo', {
        sortType: this.sortType,
        commodityNo: this.queryForm.commodityNo || '',
        commodityName: this.queryForm.commodityName || '',
        sku: this.queryForm.sku || '',
        categoryId: this.queryForm.categoryId || '',
        page: this.page,
        pageSize: this.pageSize
      }).then(res => {
        if (res.responseCode === '0000') {
          this.tableData = res.data.list
          this.total = res.data.total
        } else {
          this.$message.error({
            duration: this.$store.state.duration,
            message: res.responseMsg
          })
        }
        this.$store.commit('setLoading', false)
      }).catch(err => {
        console.error(err)
        this.$store.commit('setLoading', false)
      })
    },
    // 获取商品分类
    getCategorys () {
      this.$http.post(this.$api + '/commodity/findAllCommodityCategory', {}).then(res => {
        if (res.responseCode === '0000') {
          this.categoryList = res.data
        } else {
          this.$message.error({
            duration: this.$store.state.duration,
            message: res.responseMsg
          })
        }
      }).catch(err => {
        console.error(err)
      })
    },
    // 查看详情
    check (scope) {
      this.$router.push({
        path: '/stock/stockDetail',
        query: {
          commodityId: scope.row.commodityId,
          pg: this.page,
          size: this.pageSize
        }
      })
    },
    // 分页
    sizeChange (size) {
      this.pageSize = size
      this.getData()
    },
    pageChange (page) {
      this.page = page
      this.getData()
    },
    openDialog () {
      this.importDialog = true
      this.$nextTick(() => {
        this.resultList = []
        this.$refs.fileUploader.clearFiles()
      })
    },
    // 导出商品
    exportGoods () {
      let param = {
        page: this.page || 1,
        pageSize: this.pageSize || 10,
        sortType: this.sortType || 1,
        token: this.$store.state.token
      }
      let url = this.$api + '/stock/exportStockInfo?' + QS.stringify(sign(param))
      window.location.href = url
    },
    // 导入商品
    importGoods () {
      this.$http.post(this.$api + '/stock/importStock', {
        fileUrl: this.fileUrl || ''
      }).then(res => {
        if (res.responseCode === '0000') {
          this.resultList = res.data
        } else {
          this.$message.error({
            duration: this.$store.state.duration,
            message: res.responseMsg
          })
        }
      }).catch(err => {
        console.error(err)
      })
    },
    // 检查文件大小不超过2M
    beforeUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!')
      }
      return isLt2M
    },
    // 上传成功
    uploadSuccess (res, file) {
      this.fileUrl = res.data
    },
    // 超出上传限制
    overUpload () {
      this.$message.error({
        duration: this.$store.state.duration,
        message: '最多只能上传一个文件，如需覆盖请先删除之前的文件再上传！'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.flex-box {
  display: flex;
  justify-content: space-between;
  .f1 {
    margin-right: 10px;
    flex: 1;
  }
}
.upload-result-box {
  margin: 20px 0;
  padding: 10px;
  border: solid 1px #e5e5e5;
  .result-list {
    margin: 0;
    list-style-type: none;
    li {
      height: 20px;
      line-height: 20px;
      font-size: 12px;
    }
  }
}
</style>
